package cn.edu.hncst.controller;

import cn.edu.hncst.service.UserService;
import cn.edu.hncst.service.impl.UserServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/deleteUserServlet")
public class DeleteUserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       //获取单个id
        String id = req.getParameter("id");
        //获取多个id
        String uids = req.getParameter("uids");
        if (uids != null) {
            //删除多个
            deleteUsers(req, resp, uids);
        } else if (id != null) {
            //删除单个
            deleteUser(req, resp, id);
        }
    }

    /**
     * 删除单条数据
     *
     * @param req
     * @param resp
     * @param id
     * @throws ServletException
     * @throws IOException
     */
    private void deleteUser(HttpServletRequest req, HttpServletResponse resp, String id) throws ServletException, IOException {
        UserService userService = new UserServiceImpl();
        int i = userService.deleteById(Integer.valueOf(id));
        if (i == 1) {
            //删除后跳转
            resp.sendRedirect(req.getContextPath() + "/pageQueryServlet");
        }
    }

    /**
     * 批量删除
     * @param req
     * @param resp
     * @param uids
     * @throws ServletException
     * @throws IOException
     */
    private void deleteUsers(HttpServletRequest req, HttpServletResponse resp, String uids) throws ServletException, IOException {
        //切割字符串
        String[] uid = uids.split(",");
        UserService userService = new UserServiceImpl();
        //将信息批量删除
        int[] ints = userService.deleteByIds(uid);
        for (int anInt : ints) {
            if(anInt == 0){
                req.getRequestDispatcher("/error.jsp").forward(req,resp);
            }
        }

        resp.sendRedirect(req.getContextPath() + "/pageQueryServlet");
    }
}
